import { useEffect, useCallback } from 'react'
import { useSearchUIState } from '../../../../store/hooks/useSearchUIState';
import { useSearchUIDispatch } from '../../../../store/hooks/useSearchUIDispatch';
import { useJumpResult } from '../../../../store/hooks/useJumpResult';
import { useFetchHistoryData, useSearchDataSource } from './resultHooks'
const SearchResultList = (props: { hoverIndex?: number }) => {
  const { keyword = '', showSearchResultPanel } = useSearchUIState();
  const updateUIState = useSearchUIDispatch();
  const fetchHistoryAction = useFetchHistoryData();
  const { fetchSearchDataSource, searchDataSource,clear, cancel } = useSearchDataSource(fetchHistoryAction);

  useEffect(() => {
    
    if (showSearchResultPanel && keyword) {
      fetchSearchDataSource(keyword);
    }
    if (showSearchResultPanel && !keyword) {
      cancel()
      clear()
    }
  }, [keyword, showSearchResultPanel, fetchSearchDataSource]);
  useEffect(() => {
    updateUIState({
      historyDataLength: searchDataSource.length - 1
    })
  }, [searchDataSource])
  const setKeyword = useCallback(
    (nextKeyword) => {
      updateUIState({
        keyword: nextKeyword,
        keywords: [nextKeyword],
      });
    },
    [updateUIState],
  );

  const onJumpResult = useJumpResult(setKeyword);
    
  const show = searchDataSource.length > 0;
  return show ? (
    <ul className="search-result-list">
      {searchDataSource.map((item, index) => {
        // 联想搜索词直接显示, 不替换
        return (
          <li
            key={index}
            className={
              props.hoverIndex !== undefined ? (index == props.hoverIndex ? 'hover' : '') : ''
            }
            onClick={() => {
              let key = item?.replace(/(<([^>]+)>)/gi, '') || '';
              onJumpResult(key, [key]);
            }}
            dangerouslySetInnerHTML={{ __html: item }}
          />
        );
      })}
    </ul>
  ) : null;
};
export default SearchResultList